package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.vo.LoginVoWM;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserService apUserService;
    @Override
    public ResponseResult login(WmLoginDto dto) {
       //TODO
        String hashpw = BCrypt.hashpw(dto.getPassword(), BCrypt.gensalt());
        LambdaQueryWrapper<WmUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmUser::getName,dto.getName());
        List<WmUser> list = apUserService.list(lambdaQueryWrapper);
        for (WmUser apUser : list) {
            String password = apUser.getPassword();
            if (BCrypt.checkpw(dto.getPassword(), password)){
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                LoginVoWM loginvo=new LoginVoWM();
                loginvo.setUser(apUser);
                loginvo.setToken(token);
                return ResponseResult.okResult(loginvo);
            }
        }
        return ResponseResult.errorResult(404,"用户名或密码错误");
    }
}